package example.controller;

import com.alibaba.fastjson.JSON;
import com.mysql.cj.util.StringUtils;
import example.pojo.SysRole;
import example.pojo.SysUser;
import example.service.RoleService;
import example.service.SupplierService;
import example.service.UserService;
import example.util.Page;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;

@Controller
@RequestMapping("/user")
@MultipartConfig(maxFileSize = 1024 * 1024 * 1)
public class UserController extends BaseController {
    @Resource
    private UserService userService;
    @Resource
    private RoleService roleService;
    @Resource
    private SupplierService supplierService;
    private Logger logger = Logger.getLogger(UserController.class);

    //跳转到登陆页面
    @RequestMapping(value = "/toLogin")
    public String login() {
        logger.debug("跳转到登陆页面");
        return "login";
    }

    //登录
    @PostMapping("/login")
    public String doLogin(Model model, HttpServletRequest req, HttpServletResponse resp, HttpSession session,
                          @RequestParam String account, @RequestParam String password) {
        logger.debug("登录方法");
        //调用service方法进行用户匹配
        SysUser sysUser = userService.login(account, password);
        if (sysUser != null) {
            //登陆成功进入主页面
            //将登录用户放入session
            session.setAttribute("USER_SESSION", sysUser);
            session.setAttribute("user", sysUser);
            model.addAttribute("sysUser", sysUser);

            //清除异常
            req.setAttribute("e", null);
            return "frame";
        } else {
            //用户不存在 登陆失败 跳转到登陆页面
            throw new RuntimeException("用户名不存在");
        }
    }

    //捕获异常添加异常信息
    @ExceptionHandler(value = {RuntimeException.class})
    public String handlerException(RuntimeException e, HttpServletRequest req) {
        req.setAttribute("e", e);
        return "login";
    }

    //退出登录
    @PostMapping("/logout")
    public String logout(HttpServletRequest req, HttpServletResponse resp, HttpSession session) {
        session.removeAttribute("user");
        session.removeAttribute("USER_SESSION");
        session.invalidate();
        return "login";
    }

    //跳转到首页
    @RequestMapping("/toMain")
    public String main(HttpSession session) {
        if (session.getAttribute("USER_SESSION") == null) {
            //重定向到登陆页面接口
            return "login";
        }
        return "frame";
    }

//    //捕获异常信息 跳转到error页面
//    @ExceptionHandler(value = {RuntimeException.class})
//    public String handlerException(RuntimeException e,HttpServletRequest req){
//        req.setAttribute("e",e);
//        return "error";
//    }


    //跳转修改
    @GetMapping("/toUpdate")
    public String toUpdate(@RequestParam int uid, Model model) {
        logger.debug("跳转到修改用户信息页面");
        SysUser sysUser = userService.getUserByIdOrAccount(uid, null);
        model.addAttribute("sysUser", sysUser);
        return "sysUser/update";
    }

    //修改用户信息
    @PostMapping(value = "/update")
    public String update(SysUser sysUser, HttpSession session, HttpServletResponse resp, HttpServletRequest req) throws IOException {
        logger.debug("修改用户信息");
        PrintWriter out = resp.getWriter();
        int id = Integer.parseInt(req.getParameter("id"));
        String account = req.getParameter("account");
        SysUser userId = userService.getUserByIdOrAccount(id, account);
        String realName = req.getParameter("realName");
        String sexStr = req.getParameter("sex");
        String birthdayStr = req.getParameter("birthday");
        String phone = req.getParameter("phone");
        String address = req.getParameter("address");
        String roleId = req.getParameter("roleId");
        SysUser user = new SysUser(userId.getId(), account, realName, null, Integer.parseInt(sexStr), birthdayStr, phone, address, Integer.parseInt(roleId), 1, null, null);
        int count = userService.upd(user);
        if (count > 0) {
            System.out.println("修改成功");
            return "redirect:/user/list";
        } else {
            System.out.println("修改失败");
            return "redirect:/user/list";
        }
    }

    //获取用户信息
//    @GetMapping(value = "/view/{id}")
//    public String view(Model model,@PathVariable int id){
//        model.addAttribute("sysUser",userService.getUserByIdOrAccount(id,null));
//        return "sysUser/view";
//    }

    //获取用户信息
    @ResponseBody
    @GetMapping(value = "/{id}/view", produces = {"application/json;charset=UTF-8"})
    public Object view(@PathVariable int id) {
        logger.info("根据id查询用户详情id：" + id);
        String sysUserJSON = "";
        if (id == 0) {
            return "nodate";
        } else {
            try {
                SysUser sysUser = userService.getUserByIdOrAccount(id, null);
                sysUserJSON = JSON.toJSONString(sysUser);
                logger.debug("用户信息转换为JSON：" + sysUserJSON);
            } catch (Exception e) {
                e.printStackTrace();
                return "failed";
            }
            return sysUserJSON;
        }
    }

    @ResponseBody
    @GetMapping(value = "/userExist")
    public Object accountExist(@RequestParam String account, HttpServletRequest req) {
        logger.debug("验证用户名account=" + account + "的用户是否存在");
        HashMap<String, Object> resultMap = new HashMap<>();
        if (StringUtils.isNullOrEmpty(account)) {
            resultMap.put("exist", 1);
        } else {
            resultMap.put("exist", userService.accountExist(account));
        }
        return JSON.toJSONString(resultMap);
    }


    //查询所有用户
    @RequestMapping("/list")
    public String list(Model model, @RequestParam(defaultValue = "1") Integer pageIndex, HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取参数
        String queryRealName = req.getParameter("queryRealName");
        String queryRoleIdStr = req.getParameter("queryRoleId");
        //设置分页参数
        Page<SysUser> userPage = new Page<>();
        //设置总数据量
        userPage.setTotalPage(userService.count(queryRealName, queryRoleIdStr == null || queryRoleIdStr.equals("") ? null : Integer.parseInt(queryRoleIdStr)));
        //设置总页数
        userPage.setTotalPageSize();
        //设置当前页码
        userPage.setPageIndex(pageIndex);
        //获取当前页数据
        userPage.setList(userService.pageSelectUser(userPage.getPageIndex(), userPage.getPageSize(), queryRealName, queryRoleIdStr == null || queryRoleIdStr.equals("") ? null : Integer.parseInt(queryRoleIdStr)));
        //数据回显
        req.setAttribute("queryRealName", queryRealName);
        req.setAttribute("queryRoleId", queryRoleIdStr);
        List<SysRole> roleList = roleService.roleList();
        req.setAttribute("roleList", roleList);
        req.setAttribute("userList", userPage.getList());

        req.setAttribute("totalPageCount", userPage.getTotalPageSize());
        req.setAttribute("totalCount", userPage.getTotalPage());
        req.setAttribute("currentPageNo", userPage.getPageIndex());

        return "sysUser/list";
    }

    //跳转到添加用户页面
    @GetMapping("/toAdd")
    public String toAdd(@ModelAttribute("sysUser") SysUser sysUser) {
        return "sysUser/add";
    }

//    @PostMapping("/doAdd")
//    public String add(@RequestParam(value = "attachs", required = false) MultipartFile[] attachs, @Valid SysUser sysUser, BindingResult bindingResult, HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
//        //企业营业执照
//        String idPic = null;
//        //组织机构代码证
//        String workPic = null;
//        //异常信息
//        String errorInfo = null;
//
//        boolean flag = true;
//        //文件的存储路径
//        String path = req.getSession().getServletContext().getRealPath("statics" + File.separator + "upload");
//        logger.info("文件的存储路径：" + path);
//        for (int i = 0; i < attachs.length; i++) {
//            //拿取单个文件
//            MultipartFile attach = attachs[i];
//            //文件不为为空时进入
//            if (!attach.isEmpty()) {
//                if (i == 0) {
//                    errorInfo = "uploadFileError";
//                } else {
//                    errorInfo = "uploadWpError";
//                }
//                String oldFileName = attach.getOriginalFilename();  //获取原文件名
//                logger.info("原文件名：" + oldFileName);
//                //获取原文件后缀
//                String prefix = FileNameUtils.getExtension(oldFileName);
//                logger.info("原文件后缀:" + prefix);
//                //文件大小限制
//                int filesize = 500000;
//                logger.debug("上传文件大小：" + attach.getSize());
//                //上传文件大小不得超过500kb
//                if (attach.getSize() > filesize) {
//                    req.setAttribute(errorInfo, " * 上传文件大小不得超过500kb");
//                    flag = false;
//                    //规定上传文件格式
//                } else if (prefix.equalsIgnoreCase("jpg")
//                        || prefix.equalsIgnoreCase("png")
//                        || prefix.equalsIgnoreCase("jpeg")
//                        || prefix.equalsIgnoreCase("pneg")) {
//                    String fileName = System.currentTimeMillis() + RandomUtils.nextInt(1000000) + "_Personal." + prefix;
//                    logger.debug("新文件名称：" + fileName);
//                    //设置路径
//                    File targetFile = new File(path);
//                    //如果目录不存在则创建
//                    if (!targetFile.exists()) {
//                        targetFile.mkdirs();
//                    }
//                    //保存
//                    try {
//                        //将接
//                        // 收到的文件传递给指定的目录
//                        attach.transferTo(new File(targetFile, fileName));
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                        req.setAttribute(errorInfo, "* 上传失败");
//                        flag = false;
//                    }
//                    if (i == 0) {
//                        companyLicPic = File.separator + "statics" + File.separator + "upload" + File.separator + fileName;
//                    } else if (i == 1) {
//                        orgCodePic = File.separator + "statics" + File.separator + "upload" + File.separator + fileName;
//                    }
//                    logger.debug("idPicPath:" + companyLicPic);
//                    logger.debug("workPicPath:" + orgCodePic);
//                } else {
//                    req.setAttribute(errorInfo, " * 上传图片格式不正确");
//                    flag = false;
//                }
//            }
//        }
//        //图片成功上传
//        if (flag) {
//            Supplier supplier = new Supplier();
//            //获取参数
//            String supCode = req.getParameter("supCode");
//            supplier.setSupCode(supCode);
//            String supName = req.getParameter("supName");
//            supplier.setSupName(supName);
//            String supDesc = req.getParameter("supDesc");
//            supplier.setSupDesc(supDesc);
//            String supContact = req.getParameter("supContact");
//            supplier.setSupContact(supContact);
//            String supPhone = req.getParameter("supPhone");
//            supplier.setSupPhone(supPhone);
//            String supAddress = req.getParameter("supAddress");
//            supplier.setSupAddress(supAddress);
//            String supFax = req.getParameter("supFax");
//            supplier.setSupFax(supFax);
//            supplier.setCompanyLicPicPath("companyLicPic");
//            supplier.setOrgCodePicPath("orgCodePic");
//
//            if (supplierService.add(supplier) > 0) {
//                System.out.println("供货商数据添加成功");
//                return "redirect:/supplier/list";
//            } else {
//                System.out.println("供货商数据添加失败");
//                return "redirect:/supplier/list";
//            }
//        }
//        throw new RuntimeException("供货商数据添加失败");
//    }


    //跳转到异常处理页面
    @RequestMapping(value = "/toSysError")
    public String sysError() {
        return "sysUser/sysError";
    }

    //跳转至密码修改页
    @GetMapping(value = "/toUpdPwd")
    public String toUpdPwd() {
        logger.info("进入修改密码页面");
        return "sysUser/updatePassword";
    }

    //修改用户密码
    @PostMapping(value = "/updPwd")
    private String savePassword(HttpServletRequest req) throws ServletException, IOException {
        if (req.getSession().getAttribute("user") == null) {
            System.out.println("用户信息丢失，请重新登录试试吧？");
        }
        int id = ((SysUser) req.getSession().getAttribute("user")).getId();
        String newPassword = req.getParameter("newPassword");
        if (userService.updatePwd(id, newPassword) > 0) {
            System.out.println("密码修改成功");
            req.getSession().removeAttribute("user");
            req.getSession().invalidate();
            return "login";
        } else {
            System.out.println("密码修改失败");
            return "frame";
        }
    }

    //验证用户输入密码是否正确
    @ResponseBody
    @PostMapping(value = "/checkOldPwd/{oldPassword}")
    private String checkOldPwd(HttpServletRequest req, @PathVariable String oldPassword) throws ServletException, IOException {
        int id = ((SysUser) req.getSession().getAttribute("user")).getId();
        logger.info("验证用户密码是否正确 pwd:" + oldPassword);
        String pwdJSON = "";
        if (req.getSession().getAttribute("user") == null) {
            pwdJSON = "sessionerror";
            logger.info("用户session过期");
        }
        if (oldPassword == null || oldPassword.equals("")) {
            pwdJSON = "error";
            logger.info("旧密码为空");
        }


        if (userService.checkOldPwd(id, oldPassword) > 0) {
            pwdJSON = "true";
        } else {
            pwdJSON = "false";
        }
        return pwdJSON;
    }
}